package com.zzy.filter;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import javax.sql.rowset.serial.SerialBlob;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.sql.*;

/**
 * 使用 String 读取 数据库 使用 blob 存
 */
public class TypeHanderBlobString extends BaseTypeHandler<String> {

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, String str, JdbcType jdbcType) throws SQLException {
        ByteArrayInputStream bis = null;
        try {
            bis = new ByteArrayInputStream( str.getBytes() );
        } catch (Exception e) {
            throw new RuntimeException("bytes Error!");
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    throw new RuntimeException(e.getMessage());
                }
            }
        }
        preparedStatement.setBinaryStream(i, bis);
    }

    @Override
    public String getNullableResult(ResultSet resultSet, String s) throws SQLException {
        Blob blob =  resultSet.getBlob(s);
        if(blob==null){
            return null;
        }
        return blobToString( blob);
    }

    @Override
    public String getNullableResult(ResultSet resultSet, int i) throws SQLException {
        Blob blob =  resultSet.getBlob(i);
        if(blob==null){
            return null;
        }
        return blobToString( blob);
    }

    @Override
    public String  getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        Blob blob = callableStatement.getBlob(i);
        if(blob==null){
            return null;
        }
        return blobToString( blob);
    }


    public  String blobToString(Blob blob) {
        String reString = "";
        if(blob!=null){
            try{
                reString = new String(blob.getBytes((long)1, (int)blob.length()));
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return reString;
    }
}
